<template>
  <div class="app-container">
    <el-form :model="materialModel" label-width="80px" ref="materialModel" :rules='rules'>
      <el-row>
        <el-col :span ="8">
          <el-form-item prop="name" label="资料名称">
            <el-input v-model="materialModel.name" icon="search" name="title" placeholder="请输入名字"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item prop="appOid" label="资料分类" label-width="80px">
            <el-select v-model="materialModel.appOid" placeholder="请选择" style="width: 160px;">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="文件上传" prop="url">
        <Input id="upClass" :value="materialModel.attachment.title" v-model="materialModel.attachment.url" type="text" disabled="true" placeholder="请选择文件路径" style="width:300px"></Input>
        <input id="inputFile" class="file" name="file" value="请选择2文件" type="file" style="width:60px;float:right;height:36px;position:absolute;opacity:0;cursor:pointer;padding:20px" @change="update"></input>
        <el-button style="cursor:pointer">浏览</el-button><span><img v-show="imgShow" src="http://qiniu.zhonglongedu.com/1539238021539" style="width: 50px;height: 50px;width: 50px;height: 50px;position: absolute;top: -5px;left: 510px;"></span>
      </el-form-item>
    </el-form>
    <el-button type="primary" style="margin-top: 8px;margin-left: 20px;" @click="submit(true)">确定</el-button>
    <el-button v-show="!isEdit" type="primary" style="margin-top: 8px;margin-left: 20px;" @click="submit(false)">添加下一个</el-button>
  </div>
</template>

<script>
import { fetchList } from "@/api/article";
import axios from "axios";
import api from "@/api/upload";
import { Message } from "element-ui";
import { cloneDeep, defaultsDeep } from "lodash";

const defaultMaterialModel = {
  name: "",
  appOid: "",
  url: "",
  attachment: {
    contentType: {
      code: ""
    },
    url: "",
    title: ""
  }
};
export default {
  data() {
    return {
      options: [],
      materialModel: cloneDeep(defaultMaterialModel),
      imgShow: false,
      isEdit: false,
      rules: {
        name: [{ required: true, message: "不能为空", trigger: "blur" }],
        appOid: [{ required: true, message: "不能为空", trigger: "change" }]
        // url: [{ required: true, message: "不能为空", trigger: "change" }]
      }
    };
  },
  created() {},
  mounted() {
    api.appList().then(response => {
      response.map((item, index) => {
        this.options.push({
          label: item.name,
          value: item.oid
        });
      });
    });
    this.loadData();
  },
  methods: {
    loadData() {
      const oid = this.$route.query.oid;
      this.isEdit = !!oid;
      if (oid) {
        api.materialIdShow(oid).then(response => {
          this.materialModel = cloneDeep(response);
        });
      }
    },
    submit(from) {
      this.$refs["materialModel"].validate(valid => {
        if (valid) {
          api.saveMaterial(this.materialModel).then(({ success, data }) => {
            this.$message({
              showClose: true,
              message: "添加成功！",
              type: "success"
            });
            if (from) {
              this.$router.push("/upload");
            } else {
              this.materialModel = cloneDeep(defaultMaterialModel);
              this.materialModel.appOid = '请选择'
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    update(e) {
      this.imgShow = true;
      const fileData = e.target.files[0];
      if (fileData.type.indexOf(".xlsx") != -1) {
        document.getElementById("upClass").value = "";
        this.$message({
          showClose: true,
          message: "只能上传image，pdf，doc，video，audio的文件！",
          type: "error"
        });
        return false;
      }
      axios.get("/qiniu/upload-token").then(res => {
        const data = new FormData();
        const nameDate = new Date().getTime();
        const key = nameDate;
        data.append("name", nameDate);
        data.append("key", key);
        data.append("token", res.data.uploadToken);
        data.append("file", fileData);
        axios
          .post("http://upload.qiniu.com", data, { withCredentials: false })
          .then(response => {
            this.imgShow = false;
            this.materialModel.attachment.url =
              "http://qiniu.zhonglongedu.com/" + response.data.key;
            let result = fileData.type.toLowerCase();
            if (result.indexOf("image") >= 0) {
              result = "IMAGE";
            } else if (result.indexOf("video") >= 0) {
              result = "VIDEO";
            } else if (result.indexOf("audio") >= 0) {
              result = "AUDIO";
            } else {
              result = "DOC";
            }
            this.materialModel.attachment.contentType.code = result;
            this.materialModel.attachment.title = fileData.name;
          });
      });
    }
  }
};
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}
#upClass {
  width: 420px;
  height: 35px;
  -webkit-appearance: none;
  background-color: #fff;
  background-image: none;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  color: #606266;
  display: inline-block;
  font-size: inherit;
  line-height: 40px;
  outline: 0;
  padding: 0 15px;
  -webkit-transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  width: 100%;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
